//
//  InPlayerViewController.m
//  Inner  Voice
//
//  Created by 徐海宇 on 16/2/27.
//  Copyright © 2016年 徐海宇. All rights reserved.
//



#import "InPlayerViewController.h"

#import "XCHudHelper.h"

#import "InPlayer.h"

#import "AppDelegate.h"

#import "InPlayerTableViewCell.h"

#import "InHistoryViewController.h"

#import "InSoundTool.h"

#import "InSound.h"

#import "InLoginViewController.h"

#import "InSoundPlayingViewController.h"

#import "InFavouriteViewController.h"

#import "InLocalCacheViewController.h"

#import "UIImageView+WebCache.h"

#import <UMSocial.h>

#define kCellIdenticy @"cell"

#define player  [InPlayer sharedInstance]

#define InScreenWidth [UIApplication sharedApplication].delegate.window.frame.size.width

#define InScreenHeight [UIApplication sharedApplication].delegate.window.frame.size.height

@interface InPlayerViewController ()<UMSocialUIDelegate,UITableViewDataSource,UITableViewDelegate>

@property (weak, nonatomic) IBOutlet UIView *myView;

@property (weak, nonatomic) IBOutlet UIButton *detailButton;

@property (weak, nonatomic) IBOutlet UIButton *playTypeBtn;

@property (weak, nonatomic) IBOutlet UIView *ButtonView;
@property (weak, nonatomic) IBOutlet UIImageView *iconimageV;

@property (weak, nonatomic) IBOutlet UITableView *mytabelView;

@property (nonatomic,strong)NSArray *cellNameArray;

@property (nonatomic,strong)NSArray *cellIconArray;

@property (nonatomic, strong)NSArray *songlistArray;

@property (nonatomic,strong)NSMutableArray *soundArray;//用来存贮单曲循环的
@property (weak, nonatomic) IBOutlet UIButton *lastBtn;

@property (weak, nonatomic) IBOutlet UIButton *nextBtn;

@property (nonatomic,strong)NSMutableArray *resaveArray;//用来保存正在播放的数组

@property (strong, nonatomic) IBOutlet UIButton *resumeOrPlayBtn;

@end

@implementation InPlayerViewController

- (NSArray *)songlistArray {
    if (_songlistArray == nil) {
        _songlistArray = [NSArray array];
    }
    return _songlistArray;
}

- (NSMutableArray *)resaveArray {
    if (_resaveArray == nil) {
        _resaveArray = [NSMutableArray array];
    }
    return _resaveArray;
}

- (NSMutableArray *)soundArray {
    if (_soundArray == nil) {
        _soundArray = [NSMutableArray array];
    }
    return _soundArray;
}

- (NSArray *)cellNameArray {
    if (_cellNameArray == nil) {
        _cellNameArray = @[@"  正在播放",@"  喜欢的音乐",@"  历史播放列表",@"  本地离线缓存"];
    }
    return _cellNameArray;
}

- (NSArray *)cellIconArray {
    if (_cellIconArray == nil) {
    }
    return _cellIconArray;
}

- (NSMutableArray *)playingSoundArray {//存储正在播放的歌曲的模型
    if (_playingSoundArray == nil) {
        _playingSoundArray = [NSMutableArray array];
//        _playingSoundArray = [NSMutableArray array];
    }
    return _playingSoundArray;
}

//网络图片的加载  第三方库
- (void)loadImageWithStr:(NSString*)str WithImageView:(UIImageView *)imageView{
    
    NSURL *url = [NSURL URLWithString:str];
//    给imaageView加载网络图片，之前先用1.jpg
    [imageView sd_setImageWithURL:url placeholderImage:[UIImage imageNamed:@"1.jpg"]];
    
}

- (void)viewWillAppear:(BOOL)animated {
    
    [super viewWillAppear:animated];
    
    [self loadImageWithStr:self.inSound.inSound_icon Withimag:self.iconimageV];
    NSLog(@"insound_icon %@",self.inSound.inSound_icon);
    
    [self.detailButton setTitle:self.inSound.inSound_name forState:UIControlStateNormal];
    
    NSLog(@"  播放器主界面 icon  %@",self.inSound.inSound_icon);

}
- (void)clipImageCorrner {
    
    self.iconimageV.layer.borderColor = [[UIColor lightGrayColor]CGColor];
    //    圆的边框宽度
//    self.iconButton.layer.borderWidth = 1;
    
    self.iconimageV.layer.cornerRadius = self.iconimageV.frame.size.width*0.5;

    self.iconimageV.clipsToBounds = YES;
}

- (void)zhuanquan {
    CABasicAnimation * animation =[CABasicAnimation animation];
    animation.keyPath =@"transform.rotation";
    animation.toValue =@(M_PI *2);
    animation.duration =30.0;//30s转一圈
    animation.fillMode =kCAFillModeForwards;
    animation.repeatCount = MAXFLOAT;//无限圈
    // 控制layer停止动画的属性 假动画
    animation.removedOnCompletion = NO;
    [self.iconimageV.layer addAnimation:animation forKey:nil];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self clipImageCorrner];
    player.detegate = self;
    
    //    tableView 的 背景
    UIImageView *backImageView=[[UIImageView alloc]initWithFrame:self.view.bounds];
    backImageView.backgroundColor = [UIColor clearColor];
//    [backImageView setImage:[UIImage imageNamed:@"3434.png"]];
    self.mytabelView.backgroundView=backImageView;

    // Do any additional setup after loading the view from its nib.

   UIWindow * window = [UIApplication sharedApplication].delegate.window;
//    
//    //view
//    AppDelegate *delegate = [UIApplication sharedApplication].delegate;
//    
//    delegate.playingView = self.sliderView;
//    
//    delegate.playingView.hidden = NO;
//    
//    NSLog(@"  playing%@",delegate.playingView);
//    
    self.myView.frame = window.frame;
    
   [self.mytabelView registerNib:[UINib nibWithNibName:@"InPlayerTableViewCell" bundle:nil] forCellReuseIdentifier:kCellIdenticy];
    
    self.mytabelView.showsVerticalScrollIndicator = NO;
    self.mytabelView.delegate = self;
    self.mytabelView.dataSource = self;
    
    self.inplayer = player;
    //先保存原始的播放数组,方便后面修改
    self.resaveArray = [InSoundTool soundArray];


    
    //button的图片加载有问题
//    self.iconButton.imageView.hidden = NO;
//    [self.iconButton.imageView setFrame:CGRectMake(0, 0, self.iconButton.bounds.size.width, self.iconButton.bounds.size.height)];
//    
//    [self loadImageWithStr:self.inSound.inSound_icon WithImageView:self.iconButton.imageView];
  //  [self loadImageWithStr:self.inSound.inSound_icon WithButton:self.iconButton];
    
    NSLog(@"播放器主界面 soundicon  %@",self.inSound.inSound_icon);
    
//    NSLog(@"%@",self.iconButton.imageView);
    
  //  [self.playTypeBtn setTitle:@"顺序播放" forState:UIControlStateNormal];
    
//    http://zyvideo1.oss-cn-qingdao.aliyuncs.com/zyvd/7c/de/04ec95f4fd42d9d01f63b9683ad0
  //  [player playWithUrl:[NSURL URLWithString:@"http://7u2q8y.com2.z0.glb.qiniucdn.com/c1/179b4218361339e5ecbca4f8a337c7e0db132e1bb021cda7e592b7b544213f8190e2fa54.mp3?1447020769"] showView:self.sliderView];
    
//    [player playWithUrl:[NSURL URLWithString:((InSound *)self.playingSoundArray[self.index]).inSound_Url] showView:self.sliderView];
    
//    [InSoundTool insertInToSound:self.playingSoundArray[self.index]];
//    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(appDidEnterPlayGround) name:UIApplicationDidBecomeActiveNotification object:nil];
    //通知中心播放完成后调用的方法
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(playFinished:) name:AVPlayerItemDidPlayToEndTimeNotification object:nil];
    
}



- (void)loadImageWithStr:(NSString *)str Withimag:(UIImageView *)imag {
    
    NSURL *url = [NSURL URLWithString:str];
    
    //根据图片的url下载图片数据
    dispatch_queue_t queue = dispatch_queue_create("loadImage", NULL);//创建GCD线程队列
    dispatch_async(queue, ^{
        //异步下载图片
        UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:url]];
        //主线程刷新UI
        dispatch_async(dispatch_get_main_queue(), ^{
            imag.image = image;
        });
    });
    
}


- (void)playFinished:(NSNotification *)notify {
    
    NSLog(@"播放器主界面playFinished:%@",notify);
    
    [player stop];
    //一首歌播放完成后 播放下一首歌
    if (self.index == self.playingSoundArray.count-1) {
        self.index = 0;
    }else {
        self.index += 1;
    }
    
    [player playWithUrl:[NSURL URLWithString:((InSound *)self.playingSoundArray[self.index]).inSound_Url] showView:self.sliderView];
    
    [InSoundTool insertInToSound:self.playingSoundArray[self.index]];
    
//    [player playWithUrl:url2 showView:self.view];

}

#pragma mark - buttonClick
#warning just do it

//如何播放只是正在播放的数组的改变 其他都不变
- (IBAction)playTypeBtnClick:(id)sender {
    //如果未选中  点击选中为单曲循环模式
    if (self.playTypeBtn.selected == NO) {
        
        self.playTypeBtn.selected = YES;
        
        [self.soundArray removeAllObjects];
        
        self.playingSoundArray = self.resaveArray;
        
        NSLog(@"播放器主界面 %ld",self.playingSoundArray.count);
        
        [self.soundArray addObject:self.playingSoundArray[self.index]];
        
        self.playingSoundArray = self.soundArray;

    }else {
        //未选中状态为顺序播放
        self.playTypeBtn.selected = NO;
        //先清空
        [self.playingSoundArray removeAllObjects];
        
        self.playingSoundArray = self.resaveArray;
    }
     NSLog(@"   player.currentPlayerItem   %@",player.currentPlayerItem);
    
}



- (IBAction)backBtnClick:(id)sender {
    
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (IBAction)shareBtnClick:(id)sender {
    [UMSocialSnsService presentSnsIconSheetView:[AppDelegate shareAppdelegate].window.rootViewController
                                         appKey:@"507fcab25270157b37000010"
                                      shareText:@"你要分享的文字"
                                     shareImage:[UIImage imageNamed:@"icon.png"]
                                shareToSnsNames:[NSArray arrayWithObjects:UMShareToSina,UMShareToTencent,UMShareToRenren,nil]
                                       delegate:self];
}

#warning 连续点击上一曲 下一曲时有bug
- (IBAction)lastBtnClick:(id)sender {
    
    if (self.index == 0) {
        self.index = self.playingSoundArray.count -1;
    }else {
        self.index -= 1;
    }
    if (player) {
        [player stop];
    }

        self.lastBtn.enabled = NO;
        self.resumeOrPlayBtn.selected = NO;
        [player playWithUrl:[NSURL URLWithString:((InSound *)self.playingSoundArray[self.index]).inSound_Url] showView:self.sliderView];
        
        [self loadImageWithStr:((InSound *)self.playingSoundArray[self.index]).inSound_icon Withimag:self.iconimageV];
        // NSLog(@"insound_icon %@",self.inSound.inSound_icon);
        
        [self.detailButton setTitle:((InSound *)self.playingSoundArray[self.index]).inSound_name forState:UIControlStateNormal];
        
         NSLog(@"   player.currentPlayerItem2222   %@",player.currentPlayerLayer);
  
}


#pragma mark- delegate

- (void)lastBtnTypeChange {
    self.lastBtn.enabled = YES;
}

- (void)nexBtnTypeChange {
    self.nextBtn.enabled = YES;
}

- (IBAction)nextBtnClick:(id)sender {
    
    if (self.index == self.playingSoundArray.count - 1) {
        self.index = 0;
    }else {
        self.index += 1;
    }
    
    if (player) {
        [player stop];
    }
    
        self.nextBtn.enabled = NO;
        self.resumeOrPlayBtn.selected = NO;
        
        [player playWithUrl:[NSURL URLWithString:((InSound *)self.playingSoundArray[self.index]).inSound_Url] showView:self.sliderView];
        [self loadImageWithStr:((InSound *)self.playingSoundArray[self.index]).inSound_icon Withimag:self.iconimageV];
        // NSLog(@"insound_icon %@",self.inSound.inSound_icon);
        
        [self.detailButton setTitle:((InSound *)self.playingSoundArray[self.index]).inSound_name forState:UIControlStateNormal];
   
}

- (IBAction)resumeOrPlayBtnClick:(id)sender {
    if(self.resumeOrPlayBtn.selected == NO) {
        self.resumeOrPlayBtn.selected = YES;
        [player pause];
    }else {
        self.resumeOrPlayBtn.selected = NO;
        [player resume];
        [self zhuanquan];
    }
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


#pragma mark - tableViewDataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return self.cellNameArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    InPlayerTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kCellIdenticy forIndexPath:indexPath];
    cell.detailLabel.text = self.cellNameArray[indexPath.row];
    cell.backgroundColor=[UIColor clearColor];

    
    if (indexPath.row == 0) {
        cell.iconButton.image = [UIImage imageNamed:@"1zh.png"];
        cell.uniteBotton.image = [UIImage imageNamed:@"xia.png"];
    }
    if (indexPath.row == 1) {
        cell.iconButton.image = [UIImage imageNamed:@"2zh.png"];
        cell.uniteBotton.image = [UIImage imageNamed:@"xia.png"];
    }
    if (indexPath.row == 2) {
        cell.iconButton.image = [UIImage imageNamed:@"3zh.png"];
        cell.uniteBotton.image = [UIImage imageNamed:@"xia.png"];
    }
    if (indexPath.row == 3) {
        cell.iconButton.image = [UIImage imageNamed:@"4zh.png"];
        cell.uniteBotton.image = [UIImage imageNamed:@"xia.png"];
    }
    
    return cell;

}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 50;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row == 0) { //正在播放
        InSoundPlayingViewController *inSoundPlayingViewController = [[InSoundPlayingViewController alloc]initWithNibName:@"InSoundPlayingViewController" bundle:nil];
        
        if (self.playingSoundArray.count == 0) {
            
            UIAlertView *alerView = [[UIAlertView alloc]initWithTitle:@"提示" message:@"无正在播放的歌曲" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            
            [alerView show];
            
        }else {
            
            inSoundPlayingViewController.playingSoundArray = self.playingSoundArray;
            
            [self presentViewController:inSoundPlayingViewController animated:YES completion:nil];
        }
        
        
    }else if (indexPath.row == 1) {//我喜欢的
        InFavouriteViewController *inFavouriteController = [[InFavouriteViewController alloc]initWithNibName:@"InFavouriteViewController" bundle:nil];
        
        NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
        NSString *user_id = [userDefault valueForKey:@"u_Id"];
        
        if (user_id != nil) {
             [self presentViewController:inFavouriteController animated:YES completion:nil];
        }else {
            [self alertViewShow];
        }
       
    }else if (indexPath.row == 2) {//播放记录
        InHistoryViewController *inHistoryViewController = [[InHistoryViewController alloc]initWithNibName:@"InHistoryViewController" bundle:nil];
        
        [self presentViewController:inHistoryViewController animated:YES completion:nil];
    
    }else if (indexPath.row == 3) {//本地缓存
        InLocalCacheViewController *contro = [[InLocalCacheViewController alloc]init];
        [self presentViewController:contro animated:YES completion:nil];
    }
    
}


#pragma mark -alertView
- (void)alertViewShow {
    
    UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"提示" message:@"您还没有登录" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:@"取消", nil];
    
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    
    NSString *user_id = [userDefaults valueForKey:@"u_id"];
    
    if (user_id == nil) {
        [alertView show];
    }
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    
    if (buttonIndex == 0) {
        InLoginViewController *loginController = [[InLoginViewController alloc]initWithNibName:@"InLoginViewController" bundle:nil];
        
        [self presentViewController:loginController animated:YES completion:nil];
        
    }
    
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
